package m202405.d12;

import java.util.HashMap;
import java.util.Map;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/12 15:20
 */
public class Q142 {

    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                ListNode temp = head;
                while (temp != slow) {
                    temp = temp.next;
                    slow = slow.next;
                }
                return temp;
            }
        }
        return null;
    }

    public ListNode detectCycle1(ListNode head) {
        Map<ListNode, Integer> map = new HashMap();
        ListNode p = head;
        int i = 0;
        while (p != null) {
            if (map.containsKey(p)) {
                return p;
            }
            map.put(p, i);
            i++;
            p = p.next;
        }
        return null;
    }
}
